import React, { Component, PropTypes } from 'react';
import Echarts from 'echarts';
import { connect } from 'dva'
// import Qiniu from 'qiniu-js'
import {
  Input,
  Button,
  Select,
  Form,
  Modal,
  Row,
  Col,
  Icon,
  message,
} from 'antd';
import Style from './home.less';
import NumberPlay from '../../util/numberPlay';
import $ from 'jquery';
import Service from "../../service";
const FormItem = Form.Item;
const createForm = Form.create;
const Option = Select.Option;

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      loading: 'none',
      qiniutoken: '',
      videoSrc: '',
      videoKey: ''
    };
  }
  componentDidMount() {
    let self = this;
    const token = localStorage.getItem('token');
    self.props.e_bikeInfo({
      params: {
        token: token,
      },
      func: function (result) {
        // console.log(result)
      }
    })

    self.props.qiniuToken({
      params: {
        token: token,
      },
      func: function (result) {
        let data = result.data;
        self.setState({
          qiniutoken: data.token
        }, function () {
          self.uploaderFun(data.token);
        })

      }
    })

    // // 视频配置
    // module.exports = {
    //   AccessKey: "S4bdDzt9U6MJsfL0HGmU6Flbxu8ce2pBPF9TxYdy",
    //   SecretKey: "5notTuuyN-UIKegJ25NYZ4Vj4VuHx1eZAVJfFr_I",
    //   Bucket: "carproject",
    //   Port: 19110,
    //   UptokenUrl: token, // demo 启动后会在本地 /uptoken 上提供获取 uptoken 的接口，所以这里可以填 'token'
    //   Domain: "https://mini.hkws.fjdcgl.com/" // Bucket 的外链默认域名，在 Bucket 的内容管理里查看，如：'http://xxx.bkt.clouddn.com/'
    // }

  }
  componentWillUnmount() {
    if (this.state.timer != null) {
      clearInterval(this.state.timer);

    }
  }
  uploaderFun = (token) => {
    let self = this;
    let uploader = Qiniu.uploader({
      disable_statistics_report: false,                                   // 禁止自动发送上传统计信息到七牛，默认允许发送
      runtimes: 'html5,flash,html4',                                      // 上传模式，依次退化
      browse_button: 'uploadImage',                                       // 上传选择的点选按钮，必需
      container: 'container',                                             // 上传区域DOM ID，默认是browser_button的父元素
      max_file_size: '100mb',
      filters: { mime_types: [{ title: "Video files", extensions: "flv,mpg,mpeg,avi,wmv,mov,asf,rm,rmvb,mkv,m4v,mp4" }] },                                           // 最大文件体积限制
      flash_swf_url: 'Moxie.swf',                                         // 引入flash，相对路径
      dragdrop: false,                                                    // 关闭可拖曳上传
      chunk_size: '4mb',                                                  // 分块上传时，每块的体积
      multi_selection: false,
      uptoken: token,                                                 // 在初始化时，uptoken，uptoken_url，uptoken_func三个参数中必须有一个被设置,uptoken是上传凭证，由其他程序生成;uptoken_url是提供了获取上传凭证的地址，如果需要定制获取uptoken的过程则可以设置uptoken_func;其优先级为uptoken > uptoken_url > uptoken_func
      domain: 'http://pv1dipcz2.bkt.clouddn.com/',                                                      // bucket域名，下载资源时用到，必需
      get_new_uptoken: true,                                              // 设置上传文件的时候是否每次都重新获取新的uptoken
      auto_start: true,                                                   // 选择文件后自动上传，若关闭需要自己绑定事件触发上传
      max_retries: 3,                                                     // 上传失败最大重试次数
      save_key: true,
      resize: {                                                           // 想限制上传图片尺寸，直接用resize这个属性
        width: 300,
        height: 300
      },
      init: {
        'FilesAdded': function (up, files) {                             // 文件添加进队列后，处理相关的事情
          plupload.each(files, function (file) {
            // console.log(file)
          });
        },
        'BeforeUpload': function (up, file) {                            // 每个文件上传前，处理相关的事情
          console.log("开始上传之前");
          $(".upload-progress").show();
        },
        'UploadProgress': function (up, file) {                          // 每个文件上传时，处理相关的事情
          console.log("上传中");
          $(".upload-progress").html("上传进度:" + file.percent + "%");
        },
        'FileUploaded': function (up, file, info) {                       // 每个文件上传成功后，处理相关的事情
          console.log("上传成功");
          $(".upload-progress").hide();
          var img = new Image();
          var res = eval('(' + info.response + ')');                                  //创建一个Image对象，实现图片的预下载
          // img.src = "http://qiniu.com/" + res.key;
          // $('#video').attr('src', "http://pv1dipcz2.bkt.clouddn.com/" + res.key);
          // $("#container").append(img);
          self.setState({
            videoKey: res.key
          })
        },
        'Error': function (up, err, errTip) {
          console.log("上传出错")
        },
        'UploadComplete': function () {
          //队列文件处理完毕后，处理相关的事情
        }
      }
    });
  }
  editFun = () => {
    this.context.router.push(`/1/app/editMy`);
  }
  lasturlFun = () => {
    this.context.router.push(`/1/app/kindex`);
  }
  carlocationurlFun = () => {
    this.context.router.push(`/1/app/carlocation`);
  }
  homeurlFun = () => {
    this.context.router.push(`/1/app/kmy`);
  }

  receiveFun = (uuid, type) => {
    let self = this;
    let token = localStorage.getItem('token');
    let params = { 'uuid': uuid, 'token': token };
    $.ajax({
      url: `${Service.baseUrl}/devices/receive`,   //列表
      type: 'POST',
      data: params,
      success: function (data) {
        if (data.code == 200) {
          if (self.state.timer != null) {
            clearInterval(self.state.timer);
          }
          self.setState({
            loading: 'none'
          })
          if (data.data.status == 1) {
            if (type == 1) {
              message.success('开启成功!', 1.5);
            } else {
              message.success('关闭成功!', 1.5);
            }
          } else {
            if (type == 1) {
              message.error('开启失败!', 1.5);
            } else {
              message.error('关闭失败!', 1.5);
            }
          }

        } else {
          if (self.state.timerNum >= 8) {
            message.error(data.error, 1.5);
          }
        }
      }.bind(this),
      error: function (xhr, status, err) { }.bind(this)
    })
  }
  /* 控制提示 */
  messageConfig() {
    message.config({
      top: 100, // 消息距离顶部的位置
      duration: 2, // 默认自动关闭延时，单位秒
      maxCount: 1, // 最大显示数, 超过限制时，最早的消息会被自动关闭
    });
  }
  // 发送
  sendSubmit = () => {
    const token = localStorage.getItem('token');
    let self = this;
    let mobile = self.state.mobile;
    let videoKey = self.state.videoKey;
    if (!mobile) {
      message.error('请输入发送电话号码');
      self.messageConfig();
      return false;
    }
    if (!videoKey) {
      message.error('请拍摄视频确定');
      self.messageConfig();
      return false;
    }
    self.props.confirm({
      params: {
        token: token,
        mobile: mobile,
        video: videoKey
      },
      func: function (result) {
        Modal.success({
          title: '提交成功',
          content: '',
          okText: '确定',
          onOk: function () {
            self.context.router.push(`/1/app/kvideolist`);
          }
        });

      }
    })

  }
  // 视频清单
  videoListFun = () => {
    this.context.router.push(`/1/app/kvideolist`);
  }
  mobileInput = (e) => {
    this.setState({
      mobile: e.target.value
    })
  }
  fileUpload = (e) => {
    const token = localStorage.getItem('token');
    var xhr = new XMLHttpRequest();
    xhr.open("POST", uploadUrl, true);
    //文本类型
    xhr.setRequestHeader("Content-Type", "application/octet-stream");
    //七牛认证信息 注意空格
    xhr.setRequestHeader("Authorization", "UpToken " + qiniutoken);
    xhr.send(imgStr);
    //监听状态
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        var result = xhr.responseText;
        console.log('上传请求结果数据:' + result);
        result = JSON.parse(result);
        $("#mypic").attr("src", urlHeader + result.hash);
        $("#imgUrl").val(urlHeader + result.hash);
      }
    }
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const { data, videoData } = this.props;
    let vehicleData = data || [];
    // console.log(videoData);
    // console.log(this.props);
    return (
      <div className={Style.wrap}>
        <div className={Style.headWrap}>
          <div className={Style.navTitle}>
            最后一公里
            <span className={Style.arrowEdit} onClick={this.videoListFun}>视频清单</span>

          </div>
        </div>
        <div className={Style.conWrap}>
          <div className={Style.carBtn}>
            <Row type="flex" className={Style.row}>
              <Col span={24} order={1} >
                <span id="container">
                  <em className={Style.gobtn} id="uploadImage">
                    {this.state.videoKey &&
                      <video src={`${Service.qiniuUrl}/` + this.state.videoKey} width="100%" height="100%" controls="controls">
                        Your browser does not support the video tag.
       </video>
                    }

                    {/* <form id="uploadImage" className={Style.fileUpload} method="post" encType="multipart/form-data">
                      <input type="file" className={Style.picFile} title=" " name="image" value="" />
                      <input name='token' value={this.state.token} type='hidden' />
                    </form> */}
                  </em>
                  {this.state.videoKey &&
                    <p>重新拍摄</p>
                  }
                  {!this.state.videoKey &&
                    <p>我已送达</p>
                  }
                </span>
              </Col>
              {/* <Col span={12} order={2}>
                <span onClick={this.closeFun}>
                  <em className={Style.canclebtn}></em>
                  <p>取消派送</p>
                </span>
              </Col> */}
            </Row>
            <dl className={Style.phoneWrap}>
              <dt>发送号码：</dt>
              <dd><Input defaultValue={this.state.mobile} onChange={this.mobileInput} className={Style.grayInput} /> </dd>
            </dl>
            <div className={Style.screenBtn} onClick={this.sendSubmit}>
              <Button block>发送</Button>
            </div>
          </div>
          <p className={Style.notes}>送达之后，拍摄小视频发送给用户发起签收请求。</p>
        </div>
        <div className={Style.foot}>
          <Row type="flex">
            <Col span={8} order={1} className={Style.on} onClick={this.lasturlFun}>
              <Icon style={{ fontSize: 20 }} type="heart" theme="outlined" /><p>最后一公里</p>
            </Col>
            <Col span={8} order={2} onClick={this.carlocationurlFun}>
              <Icon style={{ fontSize: 20 }} type="environment" theme="outlined" /><p>车辆位置</p>
            </Col>
            <Col span={8} order={2} onClick={this.homeurlFun}>
              <Icon style={{ fontSize: 20 }} type="user" theme="outlined" /><p>我的</p>
            </Col>
          </Row>
        </div>
        <div className={Style.marsk} style={{ display: this.state.loading }}>
          <Icon type="loading" className={Style.loading} />
          <p className={Style.loadText}>请耐心等待...</p>
        </div>
      </div>
    )
  }
}

App.contextTypes = {
  router: React.PropTypes.object
}

function mapStateToProps(state, ownProps) {
  // console.log(state)
  return {
    videoData: state.kmodel.videoData
  }
}

function dispatchToProps(dispatch) {
  return {
    confirm(payload, params) {
      dispatch({
        type: 'kmodel/confirm',
        payload
      })
    },
    e_bikeInfo(payload, params) {
      dispatch({
        type: 'kmodel/e_bikeInfo',
        payload
      })
    },
    qiniuToken(payload, params) {
      dispatch({
        type: 'kmodel/qiniuToken',
        payload
      })
    },
  }
}
export default connect(mapStateToProps, dispatchToProps)(Form.create()(App));
